package com.example.lesson

import android.os.Bundle
import android.view.MenuItem
import android.widget.LinearLayout
import android.widget.Toolbar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.core.BaseView
import com.example.core.utils.CacheUtils
import com.example.lesson.entity.Lesson
import kotlin.reflect.KProperty

class LessonActivity : AppCompatActivity(), BaseView<LessonPresenter>, Toolbar.OnMenuItemClickListener {
    /*  private var lessonPresenter: LessonPresenter = LessonPresenter(this);

      override fun getPresenter(): LessonPresenter {
          return lessonPresenter;
      }*/

    override val p: LessonPresenter by lazy {
        LessonPresenter(this)//只会初始一次 不调用不会初始
    }

    private var lessonAdapter: LessonAdapter = LessonAdapter();
    private lateinit var refreshLayout: SwipeRefreshLayout;

    var token1: String by Saver("token1")
    var token2: String by Saver("token2")

    class Saver(var key: String) {
        operator fun getValue(lessonActivity: LessonActivity, property: KProperty<*>): String {
            return CacheUtils.get(key)!!
        }

        operator fun setValue(lessonActivity: LessonActivity, property: KProperty<*>, value: String) {
            CacheUtils.save(key, value)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lesson);

        //任何地方修改token1属性都会导致回调setValue这样达到值一定是缓存中最新值
        token1 = "123"

        var toolbar: Toolbar = findViewById(R.id.toolbar);
        toolbar.inflateMenu(R.menu.menu_lesson);
        toolbar.setOnMenuItemClickListener(this);

/*        var recyclerView: RecyclerView = findViewById(R.id.list);
        recyclerView.setLayoutManager(LinearLayoutManager(this));
        recyclerView.setAdapter(lessonAdapter);
        recyclerView.addItemDecoration(DividerItemDecoration(this, LinearLayout.VERTICAL));*/

        //run
        findViewById<RecyclerView>(R.id.list).run {
            layoutManager = LinearLayoutManager(this@LessonActivity)
            adapter = lessonAdapter
            addItemDecoration(DividerItemDecoration(this@LessonActivity, LinearLayout.VERTICAL));
        }

//run
        findViewById<SwipeRefreshLayout>(R.id.swipe_refresh_layout).run {
            refreshLayout = this
            setOnRefreshListener() { p.fetchData() }
            isRefreshing = true
        }


        p.fetchData();
    }

    fun showResult(lessons: List<Lesson>?) {
        lessonAdapter.updateAndNotify(lessons!!)
        refreshLayout.isRefreshing = false
    }

    override fun onMenuItemClick(p0: MenuItem?): Boolean {
        p.showPlayback();
        return false;
    }
}